package com.example.myapplication;

import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.ColorSpace;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {
    Bitmap srgbBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        RadioGroup radioGroup = findViewById(R.id.convert_method_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.canvas_api) {
                    CanvasConvertSRGBToP3(srgbBitmap);
                } else if (checkedId == R.id.colorspace_api){
                    ConnectorConvertSRGBToP3(srgbBitmap);
                }
            }
        });

        if (CheckSupportP3()) {
            openSupportP3();
        }

        new Handler().postDelayed(this::HandleImageDecode, 100);
    }

    void HandleImageDecode() {
        DecodePicture(getResources(), R.drawable.haidishanhuxiao,
                true,
                findViewById(R.id.p3_text),
                findViewById(R.id.p3_image));

        srgbBitmap = DecodePicture(getResources(), R.drawable.haidishanhuxiao,
                false,
                findViewById(R.id.origin_image_desc_text),
                findViewById(R.id.origin_image));

        ConnectorConvertSRGBToP3(srgbBitmap);
    }

    void ConnectorConvertSRGBToP3(Bitmap source) {
        if (source != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ColorSpace sourceColorSpace = source.getColorSpace();
            if (sourceColorSpace == null) {
                Toast.makeText(this, "获取源图片色域失败", Toast.LENGTH_LONG).show();
                return;
            }

            int[] pixels = new int[source.getWidth() * source.getHeight()];
            source.getPixels(pixels, 0, source.getWidth(), 0, 0, source.getWidth(), source.getHeight());

            float[] floats = new float[pixels.length];
            for (int i = 0; i < pixels.length; i++) {
                int alpha = Color.alpha(pixels[i]);
                int red = Color.red(pixels[i]);
                int green = Color.green(pixels[i]);
                int blue = Color.blue(pixels[i]);
                floats[i] = Color.argb(0, red, green, blue);
            }

            ColorSpace p3ColorSpace = ColorSpace.get(ColorSpace.Named.DISPLAY_P3);
            ColorSpace.Connector connector = ColorSpace.connect(sourceColorSpace, p3ColorSpace);
            float[] data = connector.transform(floats);
            for (int i = 0; i < data.length; i++) {
                pixels[i] = (int) data[i];
            }

            Bitmap p3Bitmap = Bitmap.createBitmap(
                    source.getWidth(),
                    source.getHeight(),
                    Bitmap.Config.ARGB_8888,
                    true,
                    ColorSpace.get(ColorSpace.Named.DISPLAY_P3)
            );
            p3Bitmap.setPixels(pixels, 0, p3Bitmap.getWidth(), 0, 0, p3Bitmap.getWidth(), p3Bitmap.getHeight());

            TextView convertColorSpaceText = findViewById(R.id.convert_bitmap_color_space);
            if (p3Bitmap.getColorSpace() != null) {
                convertColorSpaceText.setText(p3Bitmap.getColorSpace().getName());
            }
            ImageView imageView = findViewById(R.id.alpha0_p3_image);
            imageView.setImageBitmap(p3Bitmap);

            Toast.makeText(this, "ColorSpace api 色域转换完成", Toast.LENGTH_SHORT).show();
        }
    }

    void CanvasConvertSRGBToP3(Bitmap source) {
        if (source != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int[] pixels = new int[source.getWidth() * source.getHeight()];
            source.getPixels(pixels, 0, source.getWidth(), 0, 0, source.getWidth(), source.getHeight());
            for (int i = 0; i < pixels.length; i++) {
                int alpha = Color.alpha(pixels[i]);
                int red = Color.red(pixels[i]);
                int green = Color.green(pixels[i]);
                int blue = Color.blue(pixels[i]);
                pixels[i] = Color.argb(0, red, green, blue);
            }
            Bitmap newBitmap = Bitmap.createBitmap(
                    source.getWidth(),
                    source.getHeight(),
                    Bitmap.Config.ARGB_8888,
                    true,
                    ColorSpace.get(ColorSpace.Named.SRGB));
            newBitmap.setPixels(pixels, 0, newBitmap.getWidth(), 0, 0, newBitmap.getWidth(), newBitmap.getHeight());

            Bitmap p3Bitmap = Bitmap.createBitmap(
                    newBitmap.getWidth(),
                    newBitmap.getHeight(),
                    Bitmap.Config.ARGB_8888,
                    true,
                    ColorSpace.get(ColorSpace.Named.DISPLAY_P3)
            );

            Canvas canvas = new Canvas(p3Bitmap);
            Paint paint = new Paint();
            paint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix()));
            canvas.drawBitmap(newBitmap, 0, 0, paint);

            TextView convertColorSpaceText = findViewById(R.id.convert_bitmap_color_space);
            if (p3Bitmap.getColorSpace() != null) {
                convertColorSpaceText.setText(p3Bitmap.getColorSpace().getName());
            }
            ImageView imageView = findViewById(R.id.alpha0_p3_image);
            imageView.setImageBitmap(p3Bitmap);

            Toast.makeText(this, "canvas api 色域转换完成", Toast.LENGTH_SHORT).show();
        }
    }

    boolean CheckSupportP3() {
        TextView systemVersionText = findViewById(R.id.system_version_text);
        TextView supportP3Text = findViewById(R.id.support_p3_text);

        boolean screenWideColorGamut = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            systemVersionText.setText("系统版本：Android 11及以上");
            screenWideColorGamut = Objects.requireNonNull(getDisplay()).isWideColorGamut();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            systemVersionText.setText("系统版本：Android 8.0 ~ Android 11");
            screenWideColorGamut = getResources().getConfiguration().isScreenWideColorGamut();
        } else {
            systemVersionText.setText("系统版本：Android 8.0以下");
        }
        if (screenWideColorGamut) {
            supportP3Text.setText("是");
            supportP3Text.setTextColor(Color.GREEN);
        } else {
            supportP3Text.setText("否");
            supportP3Text.setTextColor(Color.RED);
        }
        return screenWideColorGamut;
    }

    void openSupportP3() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getWindow().setColorMode(ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT);
            if (getWindow().getColorMode() == ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT) {
                TextView windowOpenP3 = findViewById(R.id.window_open_p3_text);
                windowOpenP3.setText("是");
                windowOpenP3.setTextColor(Color.GREEN);
            }
        }
    }

    public Bitmap DecodePicture(Resources res, int resId, boolean forceDisplayP3, TextView desc, ImageView imageView) {
        // 预解码获取元数据
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        int width = imageView.getWidth();
        int height = imageView.getHeight();
        // 实际解码图片数据
        options.inJustDecodeBounds = false;
        options.inSampleSize = Math.min(options.outWidth/width, options.outHeight/height);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            options.inPreferredColorSpace = forceDisplayP3 ? ColorSpace.get(ColorSpace.Named.DISPLAY_P3) : options.outColorSpace;
        }
        Bitmap bitmap = BitmapFactory.decodeResource(res, resId, options);
        imageView.setImageBitmap(bitmap);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            desc.setText("图片色域：Android 8.0以下，默认SRGB");
        } else if (bitmap.getColorSpace() != null) {
            desc.setText("图片色域：" + bitmap.getColorSpace().getName());
        }

        return bitmap;
    }
}